import axios from 'axios'
import wx from 'weixin-js-sdk'
import { useLocation } from '@/store/location'

const wxConfig = async () => {
    const url = encodeURIComponent(window.location.href.split('#')[0])
    axios.get(`${import.meta.env.VITE_BASE_API}/config?url=${url}`).then((result: any) => {
        const { appId, timestamp, nonceStr, signature, mapApi, mapKey } = result.data.data
        const opt = { appId, timestamp, nonceStr, signature }
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            ...opt,
            jsApiList: [
                'getLocation',
                'openLocation',
                'chooseImage',
                'chooseWXPay'
            ]
        })
        wx.ready(() => {
            wx.getLocation({
                type: 'gcj02',
                success: async(res) => {
                    const { latitude, longitude } = res
                    const setLocation = { mapApi, mapKey, location: `${latitude},${longitude}` }
                    useLocation().setLocation(setLocation)
                }
            })
        })
    })
}

export default wxConfig